package com.example.yiqiuser.service.impl;


import com.example.yiqiuser.dao.UserDao;
import com.example.yiqiuser.entity.User;
import com.example.yiqiuser.service.UserService;
import com.example.yiqiuser.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * @ fileName:UserServiceImpl
 * @ description:
 * @ author:xjd
 * @ createTime:2023/3/27 20:18
 * @ version:1.0.0
 */
@Service
public class UserServiceImpl implements UserService {
    //依赖注入
    @Resource
    private UserDao userDao;


    @Override
    public User checkUser(User user) {
        List<User> userList = userDao.queryByParamLogin(user);
        if (!CollectionUtils.isEmpty(userList)) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public PageInfo queryPage(Page<User> page) {
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        return new PageInfo(userDao.queryByParam(page.getData()));
    }

    @Override
    public List<User> queryAll() {
        return userDao.queryAll();
    }

    @Override
    public User queryById(int userId) {
        //获取集合
        List<User> userList = (List<User>) userDao.queryById(userId);
        //判断集合是否为null
        if (userList != null && userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public int add(User user) {
        //加密加盐设置
//获取原来的密码
        String oldPassword = user.getPassword();
//生成盐值
        String salt = UUID.randomUUID().toString();
//生成加密密码
        Sha512Hash sha512Hash = new Sha512Hash(oldPassword, salt, 1024);
//设置加密过后的密码
        user.setPassword(sha512Hash.toString());
//盐值
        user.setSalt(salt);
        return userDao.add(user);
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }


    /**
     * 删除用户
     *
     * @param user
     * @return
     */
    @Override
    public int deleteById(User user) {
        Integer userId = user.getUserId();
        return userDao.deleteById(userId);
    }
}